package com.youxin.chat.pay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.youxin.base.BaseResultCode;
import com.youxin.common.config.YouxinCommonProperties;
import com.youxin.common.constant.MqConstant;
import com.youxin.common.constant.RedisKey;
import com.youxin.chat.pay.config.PayProperties;
import com.youxin.chat.pay.context.PayPassContext;
import com.youxin.chat.pay.context.RedPackContext;
import com.youxin.chat.pay.dto.PayRulesDto;
import com.youxin.chat.pay.entity.req.RedPackAssignReq;
import com.youxin.chat.pay.entity.req.RedPackSendReq;
import com.youxin.chat.pay.entity.vo.RedPackReceiveVo;
import com.youxin.chat.pay.entity.vo.RedReceiveItem;
import com.youxin.chat.pay.entity.vo.RedUnreceivedVo;
import com.youxin.chat.pay.enums.RedPackTypeEnum;
import com.youxin.chat.pay.enums.RedStatusEnum;
import com.youxin.chat.pay.mapper.RedReceiveMapper;
import com.youxin.chat.pay.mapper.RedSendMapper;
import com.youxin.chat.pay.mapper.UserWalletMapper;
import com.youxin.chat.pay.model.RedAssign;
import com.youxin.chat.pay.model.RedReceive;
import com.youxin.chat.pay.model.RedSend;
import com.youxin.chat.pay.model.UserWallet;
import com.youxin.chat.pay.service.PayRulesService;
import com.youxin.chat.pay.service.RedAssignService;
import com.youxin.chat.pay.service.RedPackService;
import com.youxin.chat.pay.service.manager.ImManager;
import com.youxin.chat.pay.service.manager.RedPackManager;
import com.youxin.chat.pay.service.rpc.UserService;
import com.youxin.chat.user.dto.UserInfoDto;
import com.youxin.exception.SystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * description: RedPackServiceImpl <br>
 * date: 2020/2/29 15:07 <br>
 * author: llkj <br>
 * version: 1.0 <br>
 */
@Service
public class RedPackServiceImpl implements RedPackService {

    private static final Logger logger = LoggerFactory.getLogger(RedPackServiceImpl.class);

    @Resource
    private UserWalletMapper userWalletMapper;

    @Resource
    private RedReceiveMapper redReceiveMapper;

    @Resource
    private RedSendMapper redSendMapper;

    @Resource
    private PayProperties payProperties;

    @Resource
    private RedPackManager redPackManager;

    @Resource
    private ImManager imManager;

    @Resource
    private PayRulesService payRulesService;

    @Resource
    private RedAssignService redAssignService;

    @Resource
    private UserService userService;


    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private AmqpTemplate amqpTemplate;

    @Resource
    private YouxinCommonProperties youxinCommonProperties;


    @Override
    public String sendRedPack(RedPackSendReq redPackSendDto, String userNo, String ip) throws SystemException {
        int redType = redPackSendDto.getType();
        if (!CollectionUtils.isEmpty(redPackSendDto.getSendToUserNos())) {
//            redPackSendDto.setNum(redPackSendDto.getSendToUserNos().size());
            redType = RedPackTypeEnum.NORMAL.getType().equals(redPackSendDto.getType()) ? RedPackTypeEnum.ASSIGN.getType() : RedPackTypeEnum.ASSIGNRANDOM.getType();
        }
        if (RedPackTypeEnum.NORMAL.getType().equals(redPackSendDto.getType())) {
            redPackSendDto.setAmount(redPackSendDto.getAmount().multiply(new BigDecimal(redPackSendDto.getNum())));
        }
        checkSendRule(redPackSendDto, userNo);
        RedSend redSend = buildRedPack(redPackSendDto, userNo, ip, -1);
        redSend.setRedType(redType);
        redPackManager.saveSendInfo(redSend);
        doSaveSendPlan(redSend);
        //doSendRedSendMsg(redSend);
        if (RedPackTypeEnum.ASSIGN.getType().equals(redType) || RedPackTypeEnum.ASSIGNRANDOM.getType().equals(redType)) {
            List<RedAssign> redAssigns = buildRedAssign(redSend.getId(), redPackSendDto.getSendToUserNos());
            redAssignService.saveBatch(redAssigns);
        }
        amqpTemplate.convertAndSend(MqConstant.RED_PACK_TIMEOUT_SEND_QUEUE_NAME, redSend.getId());
        return String.valueOf(redSend.getId());
    }

    @Override
    public String assignRedPack(RedPackAssignReq redPackAssignDto, String userNo, String ip) throws SystemException {
        RedPackSendReq redPackSendDto = new RedPackSendReq();
        redPackSendDto.setType(RedPackTypeEnum.ASSIGN.getType());
        redPackSendDto.setNum(redPackAssignDto.getNum());
        redPackSendDto.setAmount(redPackAssignDto.getAmount());
        redPackSendDto.setRedMsg(redPackAssignDto.getRedMsg());
        redPackSendDto.setSendTo(redPackAssignDto.getSendTo());
        redPackSendDto.setPayPass(redPackAssignDto.getPayPass());

        checkSendRule(redPackSendDto, userNo);
        RedSend redSend = buildRedPack(redPackSendDto, userNo, ip, redPackAssignDto.getType());
        redPackManager.saveSendInfo(redSend);
        doSaveSendPlan(redSend);
        List<RedAssign> list = buildRedAssign(redSend.getId(), redPackAssignDto);
        redAssignService.saveOrUpdateBatch(list);
        amqpTemplate.convertAndSend(MqConstant.RED_PACK_TIMEOUT_SEND_QUEUE_NAME, redSend.getId());
        return String.valueOf(redSend.getId());
    }

    @Override
    public void acquireRedPack(Long id, String userNo, String ip) throws SystemException {
        receiveRateLimit(id, userNo);
        RedSend redSend = redSendMapper.selectById(id);
        checkReceiveRule(redSend, userNo);
        doAcquire(redSend, userNo, ip);
    }

    @Override
    public RedPackReceiveVo getRedReceiveInfo(String redId, String userNo) throws SystemException {
        RedSend redSend = redSendMapper.selectById(redId);
        if (redSend == null) {
            throw new SystemException(BaseResultCode.RECORD_NOT_EXISTS, "红包不存在");
        }
        RedPackReceiveVo detail = new RedPackReceiveVo();
        List<RedReceiveItem> list = redReceiveMapper.selectRedReceive(redId);
        String finishTime;
        if (redSend.getRedStatus() == 1) {
            finishTime = String.valueOf(getFinishTime(redSend));
        } else {
            finishTime = "红包未领取完";
        }
        BigDecimal receiveAmount = new BigDecimal(0);
        receiveAmount = list.stream().map(RedReceiveItem::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        list.stream().forEach(item -> item.setAvatar(youxinCommonProperties.getDownloadUrl() + item.getAvatar()));
        detail.setAmount(redSend.getRedAmount());
        detail.setNum(redSend.getNum());
        detail.setReceiveAmount(receiveAmount);
        detail.setUser(list);
        detail.setTime(finishTime);
        detail.setExpired(redSend.getRedStatus() != 2 ? 0 : 1);
        detail.setRedType(redSend.getRedType());
        if (redSend.getRedType().equals(RedPackTypeEnum.ASSIGN.getType()) || redSend.getRedType().equals(RedPackTypeEnum.ASSIGNRANDOM.getType())) {
            int count = redAssignService.count(new LambdaQueryWrapper<RedAssign>().eq(RedAssign::getRedId, redId).eq(RedAssign::getUserNo, userNo));
            detail.setCanReceive(count);
        }else {
            detail.setCanReceive(1);
        }
        return detail;
    }

    @Override
    public List<RedUnreceivedVo> redUnreceivedList(String userNo, String groupNo) throws SystemException {
        boolean b = userService.isGroupAdmin(userNo, groupNo);
        if (!b) {
            throw new SystemException(BaseResultCode.HAS_NO_PERMISSION, "没有操作权限");
        }
        List<RedUnreceivedVo> list = redSendMapper.redUnreceivedList(groupNo);
        if (CollectionUtils.isEmpty(list)) {
            return list;
        }
        List<RedUnreceivedVo> result = list.stream().filter(item -> item.getCreateTime().plusMinutes(10).isBefore(LocalDateTime.now())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(result)) {
            result.stream().forEach(item -> {
                UserInfoDto userInfoDto = userService.getByUserNo(item.getUserNo());
                item.setAvatar(userInfoDto.getAvatar());
                item.setNickName(userInfoDto.getNickName());
            });
        }
        return result;
    }

    /**
     * 计算红包领取用时
     *
     * @param redSend
     * @return
     */
    private long getFinishTime(RedSend redSend) {
        Date date1 = null;
        Date date2 = null;
        try {
            //LocalDateTime转Date
            date1 = Date.from(redSend.getFinishTime().toInstant(ZoneOffset.of("+8")));
            date2 = Date.from(redSend.getCreateTime().toInstant(ZoneOffset.of("+8")));
        } catch (Exception e) {
            logger.error("计算红包完成时间错误：" + e);
            throw new SystemException(BaseResultCode.INTERNAL_ERROR, "计算红包完成时间错误");
        }
        Calendar ca1 = Calendar.getInstance();
        Calendar ca2 = Calendar.getInstance();
        ca1.setTime(date1);
        ca2.setTime(date2);
        long distanceMin = (ca1.getTimeInMillis() - ca2.getTimeInMillis()) / 1000;
        return distanceMin;
    }

    private RedSend buildRedPack(RedPackSendReq redPackSendDto, String userNo, String ip, int type) {
        RedSend redSend = new RedSend();
        redSend.setUserNo(userNo);
        redSend.setNum(redPackSendDto.getNum());
        redSend.setRedAmount(redPackSendDto.getAmount());
        redSend.setRedType(redPackSendDto.getType());
        redSend.setRedMsg(redPackSendDto.getRedMsg());
        redSend.setRedStatus(RedStatusEnum.PROCESSING.getStatus());
        redSend.setReceiveAmount(new BigDecimal(0));
        redSend.setSendTo(redPackSendDto.getSendTo());
        redSend.setClientIp(ip);
        redSend.setCreateTime(LocalDateTime.now());
        redSend.setUpdateTime(LocalDateTime.now());
        LocalDateTime expireTime = LocalDateTime.now().plus(payProperties.getRedPack().getExpireTime(), ChronoUnit.MILLIS);
        redSend.setExpireTime(expireTime);
        return redSend;
    }

    /**
     * 校验发送规则
     * 判断发送数量不能超过最大数目
     * 判断单个发送金额不能小于1分钱
     * 判断用户余额大于红包金额
     *
     * @param redPackSendDto
     * @param userNo
     */
    private void checkSendRule(RedPackSendReq redPackSendDto, String userNo) {
        if (redPackSendDto.getAmount().compareTo(new BigDecimal(0)) < 1) {
            throw new SystemException(BaseResultCode.COMMON_FAIL, "金额不能为0");

        }
        UserWallet userWallet = userWalletMapper.selectUserWalleByUserNo(userNo);
        logger.info("用户发送红包前当前余额为,userNo={},amount={}", userNo, userWallet.getUserBalance());
        if (StringUtils.isEmpty(userWallet.getPayPwd())) {
            logger.error("支付密码未设置,userNo={}", userNo);
            throw new SystemException(BaseResultCode.PAY_PASS_NOT_SET, "支付密码未设置");
        }
        boolean flag = PayPassContext.validatePass(userNo, redPackSendDto.getPayPass(), userWallet.getPayPwd());
        if (!flag) {
            logger.error("支付密码不正确,userNo={}", userNo);
            throw new SystemException(BaseResultCode.PASSWORD_INVALID, "支付密码不正确");
        }
        BigDecimal amount = redPackSendDto.getAmount();
        if (redPackSendDto.getNum() > payProperties.getRedPack().getMaxCount()) {
            logger.error("发送数目过多,num={},maxNum={},userNo={}", redPackSendDto.getNum(), payProperties.getRedPack().getMaxAmount(), userNo);
            throw new SystemException(BaseResultCode.EXCEED_LIMIT, String.format("红包个数超过%s个", payProperties.getRedPack().getMaxCount()));
        }
        BigDecimal unitAmount = redPackSendDto.getAmount().divide(new BigDecimal(redPackSendDto.getNum()), 0, BigDecimal.ROUND_HALF_UP);
        if (unitAmount.compareTo(new BigDecimal("1")) < 0) {
            logger.error("红包最小金额不能小于1分钱,num={},amount={},userNo={}", redPackSendDto.getNum(), redPackSendDto.getAmount(), userNo);
            throw new SystemException(BaseResultCode.EXCEED_LIMIT, "单个红包金额不能小于0.01元");
        }

        if (userWallet.getUserBalance().compareTo(amount) < 0) {
            logger.error("发送余额不足，amount={},balance={},userNo={}", amount, userWallet.getUserBalance(), userNo);
            throw new SystemException(BaseResultCode.BALANCE_NOT_ENOUGH, "余额不足");
        }
        PayRulesDto payRulesDto = payRulesService.info();
        if (payRulesDto.getRedPackMax().compareTo(redPackSendDto.getAmount()) < 0) {
            logger.error("红包最大金额不能超过={}，amount={},balance={},userNo={}", payRulesDto.getRedPackMax(), redPackSendDto.getAmount(), userNo);
            throw new SystemException(BaseResultCode.EXCEED_SINGLE_MAX, "发送红包金额超过最大限额");
        }
    }

    /**
     * 设置发送规则
     *
     * @param redSend
     */
    private void doSaveSendPlan(RedSend redSend) {

        if (RedPackTypeEnum.SINGLE.getType().equals(redSend.getRedType())) {
            redisTemplate.opsForList().leftPushAll(RedisKey.RED_PACK_PLAN + redSend.getId(), redSend.getRedAmount());
        } else if (RedPackTypeEnum.NORMAL.getType().equals(redSend.getRedType()) || RedPackTypeEnum.ASSIGN.getType().equals(redSend.getRedType())) {
            List<BigDecimal> amounts = new ArrayList<>();
            for (int i = 0; i < redSend.getNum(); i++) {
                BigDecimal amount = redSend.getRedAmount().divide(new BigDecimal(redSend.getNum()));
                amounts.add(amount);
            }
            redisTemplate.opsForList().leftPushAll(RedisKey.RED_PACK_PLAN + redSend.getId(), amounts);
        } else {
            List<BigDecimal> amounts = RedPackContext.splitRedPackets(redSend.getRedAmount().intValue(), redSend.getNum());
            redisTemplate.opsForList().leftPushAll(RedisKey.RED_PACK_PLAN + redSend.getId(), amounts);
        }
        redisTemplate.expire(RedisKey.RED_PACK_PLAN + redSend.getId(), payProperties.getRedPack().getExpireTime(), TimeUnit.SECONDS);

    }

    private List<RedAssign> buildRedAssign(String id, List<String> userNos) {
        List<UserInfoDto> userInfos = userService.getByUserNos(userNos);
        List<RedAssign> redAssigns = userInfos.stream().map(item -> {
            RedAssign redAssign = new RedAssign();
            redAssign.setRedId(id);
            redAssign.setNickName(item.getNickName());
            redAssign.setUserName(item.getUserName());
            redAssign.setUserNo(item.getUserNo());
            redAssign.setCreateTime(LocalDateTime.now());
            redAssign.setUpdateTime(LocalDateTime.now());
            return redAssign;
        }).collect(Collectors.toList());
        return redAssigns;
    }

    private List<RedAssign> buildRedAssign(String id, RedPackAssignReq redPackAssignDto) {
        String[] userNo = redPackAssignDto.getSendToUserNo().split(",");
        String[] userName = redPackAssignDto.getSendToUserName().split(",");
        String[] nickName = redPackAssignDto.getSendToNickName().split(",");
        List<RedAssign> list = new ArrayList<>();
        for (int i = 0; i < userNo.length; i++) {
            RedAssign redAssign = new RedAssign();
            redAssign.setRedId(id);
            redAssign.setUserNo(userNo[i]);
            redAssign.setUserName(Optional.ofNullable(userName[i]).orElse(""));
            redAssign.setNickName(Optional.ofNullable(nickName[i]).orElse(""));
            redAssign.setCreateTime(LocalDateTime.now());
            list.add(redAssign);
        }

        return list;
    }

    private void receiveRateLimit(Long id, String userNo) {
        Long count = redisTemplate.opsForValue().increment(RedisKey.RED_MAX_LIMIT + id, 1);
        redisTemplate.expire(RedisKey.RED_MAX_LIMIT + id, 1, TimeUnit.SECONDS);
        if (count > payProperties.getRedPack().getMaxCount()) {
            logger.error("1秒钟请求次数过多，count={}", count);
            throw new SystemException(BaseResultCode.EXCEED_LIMIT, "领取红包人数过多，请稍候再试");
        }
        Long operCount = redisTemplate.opsForValue().increment(RedisKey.RED_SINGLE_COUNT_LIMIT + id + "." + userNo, 1);
        redisTemplate.expire(RedisKey.RED_SINGLE_COUNT_LIMIT + id + "." + userNo, 5, TimeUnit.SECONDS);
        if (operCount > 1) {
            logger.error("单个用户不能请求多次，count={}", operCount);
            throw new SystemException(BaseResultCode.EXCEED_LIMIT, "单个用户不能多次领取");
        }
    }

    private void checkReceiveRule(RedSend redSend, String userNo) {
        if (redSend == null) {
            logger.error("红包不存在,id={}", redSend.getId());
            throw new SystemException(BaseResultCode.RECORD_NOT_EXISTS, "红包不存在");
        }
        if (!RedStatusEnum.PROCESSING.getStatus().equals(redSend.getRedStatus())) {
            logger.error("红包已领完或超过领取时间,id={}", redSend.getId());
            throw new SystemException(BaseResultCode.RECORD_NOT_EXISTS, "红包已领完或超过领取时间");
        }
        if (LocalDateTime.now().isAfter(redSend.getExpireTime())) {
            logger.error("红包已过期,id={}", redSend.getId());
            throw new SystemException(BaseResultCode.RECORD_NOT_EXISTS, "红包已领完或超过领取时间");

        }
        if (RedPackTypeEnum.SINGLE.getType().equals(redSend.getRedType())) {
            if (!redSend.getSendTo().equalsIgnoreCase(userNo)) {
                logger.error("此用户不能领取该红包，userNo={},id={}", userNo, redSend.getId());
                throw new SystemException(BaseResultCode.HAS_NO_PERMISSION, "此用户不能领取该红包");
            }
        } else {
            int count = userService.countMemberByGroupNoAndUserNo(redSend.getSendTo(), userNo);
            if (count == 0) {
                logger.error("此用户不能领取该红包，userNo={},id={}", userNo, redSend.getId());
                throw new SystemException(BaseResultCode.HAS_NO_PERMISSION, "您已被管理员禁止领取红包");
            }
            if (userService.checkUserInBlackList(userNo, redSend.getSendTo())) {
                logger.error("此用户在黑名单内，不能领取该红包，userNo={},id={}", userNo, redSend.getId());
                throw new SystemException(BaseResultCode.HAS_NO_PERMISSION, "您已被管理员禁止领取红包");
            }
        }

        if (RedPackTypeEnum.ASSIGN.getType().equals(redSend.getRedType()) || RedPackTypeEnum.ASSIGNRANDOM.getType().equals(redSend.getRedType())) {
            int count = redAssignService.count(new LambdaQueryWrapper<RedAssign>().eq(RedAssign::getRedId, redSend.getId())
                    .eq(RedAssign::getUserNo, userNo));
            if (count < 1) {
                logger.error("此用户非指定对象，userNo={},id={}", userNo, redSend.getId());
                throw new SystemException(BaseResultCode.HAS_NO_PERMISSION, "此用户非指定对象");
            }
            if (userService.countMemberByGroupNoAndUserNo(redSend.getSendTo(), userNo) < 1) {
                logger.error("此用户已不在群组内，userNo={},id={}", userNo, redSend.getId());
                throw new SystemException(BaseResultCode.HAS_NO_PERMISSION, "此用户已不在群组内");
            }
        }

        int userCount = redReceiveMapper.countByRedIdAndUserNo(redSend.getId(), userNo);
        if (userCount > 0) {
            logger.error("该用户已经领取红包，id={},userNo={}", redSend.getId(), userNo);
            throw new SystemException(BaseResultCode.RECORD_EXISTS, "该用户已经领取红包");
        }
    }

    private void doAcquire(RedSend redSend, String userNo, String ip) {
        BigDecimal amount = (BigDecimal) redisTemplate.opsForList().leftPop(RedisKey.RED_PACK_PLAN + redSend.getId());
        if (amount == null) {
            reCalculateRedPlan(redSend);
            amount = (BigDecimal) redisTemplate.opsForList().leftPop(RedisKey.RED_PACK_PLAN + redSend.getId());
        }
        if (amount == null) {
            logger.error("系统内部异常,redSend={}", JSONObject.toJSONString(redSend));
            throw new SystemException(BaseResultCode.INTERNAL_ERROR, "系统内部异常");
        }
        Long leftCount = redisTemplate.opsForList().size(RedisKey.RED_PACK_PLAN + redSend.getId());
        Integer finish = 0;
        if (leftCount == 0) {
            finish = 1;
        }
        UserInfoDto userInfo = userService.getByUserNo(userNo);
        try {
            redPackManager.saveReceiveInfo(redSend, userInfo, amount, finish, ip);
            doSendRedRecMsg(redSend, userInfo);
        } catch (Exception e) {
            redisTemplate.opsForSet().add(RedisKey.RED_PACK_PLAN + redSend.getId(), amount);
            throw e;
        }
    }

    private void reCalculateRedPlan(RedSend redSend) {
        List<RedReceive> redReceives = redReceiveMapper.selectList(new LambdaQueryWrapper<RedReceive>().eq(RedReceive::getRedId, redSend.getId()));
        BigDecimal usedAmount = new BigDecimal(0);
        int count = 0;
        for (RedReceive redReceive : redReceives) {
            usedAmount = usedAmount.add(redReceive.getAmount());
            count++;
        }
        BigDecimal leftAmount = redSend.getRedAmount().subtract(usedAmount);
        int leftCount = redSend.getNum() - count;
        if (leftAmount.compareTo(new BigDecimal(0)) <= 0 || count >= redSend.getNum()) {
            logger.error("系统内部异常，usedAmount={},count={},redSend={}", usedAmount, count, JSONObject.toJSONString(redSend));
            throw new SystemException(BaseResultCode.INTERNAL_ERROR, "系统内部异常");
        }
        if (RedPackTypeEnum.SINGLE.getType().equals(redSend.getRedType())) {
            redisTemplate.opsForList().leftPushAll(RedisKey.RED_PACK_PLAN + redSend.getId(), redSend.getRedAmount());
        } else if (RedPackTypeEnum.NORMAL.getType().equals(redSend.getRedType())) {
            BigDecimal amount = redSend.getRedAmount().divide(new BigDecimal(redSend.getNum()));
            List<BigDecimal> amounts = new ArrayList<>();
            for (int i = 0; i < leftCount; i++) {
                amounts.add(amount);
            }
            redisTemplate.opsForList().leftPushAll(RedisKey.RED_PACK_PLAN + redSend.getId(), amounts);
        } else {
            List<BigDecimal> amounts = RedPackContext.splitRedPackets(leftAmount.intValue(), leftCount);
            redisTemplate.opsForList().leftPushAll(RedisKey.RED_PACK_PLAN + redSend.getId(), amounts);
        }
        redisTemplate.expire(RedisKey.RED_PACK_PLAN + redSend.getId(), payProperties.getRedPack().getExpireTime(), TimeUnit.SECONDS);
    }

    private void doSendRedRecMsg(RedSend redSend, UserInfoDto userInfo) {
        try {
            Map<String, Object> dataMap = new HashMap<>();
            Map<String, String> userMap = new HashMap<>();
            userMap.put("nickname", userInfo.getNickName());
            userMap.put("avatar", userInfo.getAvatar());
            userMap.put("userNo", userInfo.getUserNo());
            dataMap.put("user", userMap);
            dataMap.put("msg", "领取成功");
            dataMap.put("redPackId", redSend.getId());
            if (!RedPackTypeEnum.SINGLE.getType().equals(redSend.getRedType())) {

                imManager.sendGroupRedReceiveMsg(imManager.getSystemNo(), redSend.getSendTo(), dataMap);
            } else {
                imManager.sendPrivateRedReceiveMsg(userInfo.getUserNo(), redSend.getUserNo(), dataMap);

            }
        } catch (Exception e) {
            logger.error("执行发送红包消息失败，error={}", e);
        }

    }


}
